package lang.thread;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 这个例子讲ThreadLocal
 * 
 * @author fusong
 * 
 */
public class T4 implements Runnable {

	private static final AtomicInteger uniqueId = new AtomicInteger(0);
	// ThreadLocal 实例通常是类中的 private static 字段
	private static final ThreadLocal<Integer> uniqueNum = new ThreadLocal<Integer>() {

		/*
		 * (non-Javadoc)
		 * 
		 * @see java.lang.ThreadLocal#initialValue()
		 */
		@Override
		protected Integer initialValue() {
			// TODO Auto-generated method stub
			return uniqueId.getAndIncrement();
		}

	};

	public static int getCurrentThreadId() {
		return uniqueNum.get();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// T4 t = new T4();
		// new Thread(t).start();
		// new Thread(t).start();
		// new Thread(t).start();
		// new Thread(t).start();
		/*
		 * 你会发现上面这2组写法的区别，但这个例子的运行的效果是一致的，这是由于uniqueId和uniqueNum是static类型的，
		 * 和实例化多少个对象没有关系
		 */
		new Thread(new T4()).start();
		new Thread(new T4()).start();
		new Thread(new T4()).start();
		new Thread(new T4()).start();
	}

	public void run() {
		for (int i = 0; i < 100; i++) {
			int id = T4.getCurrentThreadId();
			System.out.println("Thread:" + getCurrentThreadId());
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
